import { useState, useEffect, useContext } from 'react';
import { NavBar, Modal, Popup, Form, Input, List, InfiniteScroll, DotLoading, Toast } from 'antd-mobile';
import { AddCircleOutline } from 'antd-mobile-icons';
import AvatarImage from '../AvatarImage';

import { MySdkStoreContext } from '../../context';

import './style.scss';

export default function(props) {
  const mySdkStore = useContext(MySdkStoreContext);
  const { title, cid, getListApi, onOk, onClose } = props;
  const [list, setList] = useState([]);
  const [pagination, setPagination] = useState({});
  const [addUserForm] = Form.useForm();

  const getList = async (pageIndex) => {
    const data = await mySdkStore.sdk[getListApi]({ cid, pageIndex, pageSize: 20 });
    const { rows = [], next, current, totalItemCount } = data;
    setList(pageIndex === 1 ? rows : [...list, ...rows]);
    setPagination({ pageIndex: current, next: +next, totalItemCount });
  }

  useEffect(() => {
    getList(1);
  }, []);

  const handleOk = (userId, userInfo) => {
    onOk(userId, userInfo);
  }

  const handleAddUser = () => {
    Modal.confirm({
      title: '添加用户',
      content: <Form form={addUserForm}>
        <Form.Item name="invitedUserId" label={null} rules={[{ required: true, message: '请输入用户ID'}]}>
          <Input placeholder="请输入用户ID" />
        </Form.Item>
      </Form>,
      onConfirm: () => new Promise(async (resolve, reject) => {
        try {
          const values = await addUserForm.validateFields();
          await mySdkStore.sdk.addFriend({ ...values });
          Toast.show('好友请求已发送');
          resolve(true);
          getList(1);
        } catch(e: any) {
          if (e.errorMessage) {
            Toast.show(e.errorMessage);
          }
          reject();
        }
      }),
    });
  }

  const renderList = () => {
    return <List style={{ '--border-inner': 0 }}>
      {list.map(item => {
        return <List.Item
          key={item.userId}
          prefix={
          <>
            <AvatarImage
              src={item.avatarUrl}
              style={{ display: 'inline-block', borderRadius: 8 }}
              fit='cover'
              width={36}
              height={36}
              nickName={item.nickName}
              userName={item.userName}
              userId={item.userId}
            />
        </>}><a onClick={() => handleOk(item.userId, item)}>{item.nickName || item.userName || item.useId}</a></List.Item>
      })}
    </List>
  }

  return <Popup
    visible={true}
    bodyClassName="popupbody"
    style={{ '--z-index': 999 }}>
      <div className="selectSingleContractorComponent">
        <NavBar onBack={onClose} style={{ background: '#fff', border: 'none' }}>{ title }</NavBar>
        {/* todo: queryUsers 没有关键词搜索参数 */}
        {/* <SearchBar className="searchBar" placeholder="搜索" /> */}
        <List>
          <List.Item>
            <a onClick={handleAddUser}><AddCircleOutline style={{ marginRight: 12 }} />添加用户</a>
          </List.Item>
        </List>
        {renderList()}
        <InfiniteScroll loadMore={() => getList(pagination.pageIndex + 1)} hasMore={list.length && pagination.totalItemCount > list.length}>
          {pagination.totalItemCount > list.length ? (
              <>
                <span>Loading</span>
                <DotLoading />
              </>
            ) : ''}
        </InfiniteScroll>
      </div>
  </Popup>;
}